<template>
  <div>
    <q-list bordered class="row q-col-gutter-x-md">
      <div class="col-lg-3 col-md-5">
        <q-card>
          <q-card-section>
            <div v-if="nodeData.length == 0">暂无组织架构,请点击<a style="color:red;cursor:pointer" @click="addTree(prop = 0, addMinDialog = 1)">新增</a>添加根节点</div>
            <q-tree
              v-else
              ref="orgTree"
              :nodes="nodeData"
              node-key="id"
              label-key="name"
              :selected.sync="nodeSelected"
              selected-color="primary"
              :expanded.sync="nodeExpanded"
            >
              <template v-slot:header-root="prop">
                <div class="row items-center" style="width:100%;" id="treeName">
                  <q-badge align="top" color="orange">{{ prop.node.sonSum === null ? 0 : prop.node.sonSum }}</q-badge>--
                  <q-badge transparent align="middle" color="primary" style="position: relative;">
                    公司
                  </q-badge>
                  <div class="text-weight-bold ellipsis q-ml-xs" style="width:80%" :title="prop.node.name">{{ prop.node.name }}</div>
                </div>
              </template>
              <template v-slot:header-company="prop">
                <div class="row items-center" style="width:100%;" id="treeName">
                  <q-badge align="top" color="orange">{{ prop.node.sonSum === null ? 0 : prop.node.sonSum }}</q-badge>-
                  <q-badge transparent align="middle" color="primary">
                    子公司
                  </q-badge>
                  <div class="text-weight-bold ellipsis q-ml-xs" style="width:80%" :title="prop.node.name">{{ prop.node.name }}</div>
                </div>
              </template>
              <template v-slot:header-department="prop">
                <div class="row items-center" style="width:100%;" id="treeName">
                  <q-badge align="top" color="red">{{ prop.node.sonSum === null ? 0 : prop.node.sonSum }}</q-badge>-
                  <q-badge transparent align="middle" color="orange">
                    部门
                  </q-badge>
                  <div class="text-weight-bold ellipsis q-ml-xs" style="width:80%" :title="prop.node.name">{{ prop.node.name }}</div>
                </div>
              </template>
              <template v-slot:header-post="prop">
                <div class="row items-center" style="width:100%;" id="treeName">
                  <q-badge align="top" color="orange">{{ prop.node.sonSum === null ? 0 : prop.node.sonSum }}</q-badge>-
                  <q-badge transparent align="middle" color="positive">
                    岗位
                  </q-badge>
                  <div class="text-weight-bold ellipsis q-ml-xs" style="width:80%" :title="prop.node.name">{{ prop.node.name }}</div>
                </div>
              </template>
            </q-tree>
          </q-card-section>
        </q-card>
      </div>
      <div class="col-lg-9 col-md-7">
        <q-card>
          <q-card-section style="padding:0px;">
            <q-tabs
              v-model="tab"
              dense
              inline-label
              class="bg-grey-2 text-teal"
              align="left"
              narrow-indicator
            >
              <q-tab name="mails" style="padding:5px;font-size:20px;" label="组织明细信息" ></q-tab>
            </q-tabs>
            <q-tab-panels v-model="tab"  animated>
              <q-tab-panel name="mails">
                <div class="row" style="font-size:14px;">
                  <div class="col-lg-3 col-md-3 col-sm-5 col-xs-12 name">
                    <span class="q-my-xs text-weight-bold">名称：</span>
                    <span class="q-my-xs">{{ baseItemForm.name }}</span>
                  </div>
                  <div class="col-lg-3 col-md-3 col-sm-5 col-xs-12 name">
                    <span class="q-my-xs text-weight-bold">创建人：</span>
                    <span class="q-my-xs">{{baseItemForm.createUserName}}</span>
                  </div>
                  <div class="col-lg-3 col-md-3 col-sm-5 col-xs-12 name">
                    <span class="q-my-xs text-weight-bold">创建时间：</span>
                    <span class="q-my-xs">{{ baseItemForm.createTime }}</span>
                  </div>
                </div>
              </q-tab-panel>
            </q-tab-panels>
            <q-separator></q-separator>
            <q-tabs
              style="margin-top:20px;"
              v-model="tabs"
              dense
              inline-label
              class="bg-grey-2 text-teal"
              align="left"
              narrow-indicator
            >
            <q-tab name="item" style="padding:5px;font-size:20px;" label="联系人信息"></q-tab>
            </q-tabs>
            <q-tab-panels v-model="tabs"  animated>
              <q-tab-panel  name="item" style="padding:0px;">
                <q-table
                  class="bg-white shadow-1"
                  :data="data"
                  :columns="columns"
                  dense
                  row-key="id"
                  separator="cell"
                  :visible-columns="visibleColumns"
                  :filter="searchForm"
                  selection="multiple"
                  :selected.sync="selected"
                  :pagination.sync="pagination"
                  :rows-per-page-options="[3, 5, 10, 20]"
                  no-data-label="暂无数据"
                  table-class="h-custom"
                  @request="listGet"
                >
                  <!-- <template v-slot:top-left="props">
                    <div class="q-py-sm"  v-if="nodeSelectedHeader == 'post'">
                      <q-btn  size="sm" color="light-blue" :label="$t('新增')" @click="add"/>
                    </div>
                  </template> -->
                  <template v-slot:top-right="props">
                    <q-select
                      v-model="visibleColumns"
                      multiple
                      borderless
                      options-dense
                      :display-value="$t('显示列')"
                      emit-value
                      map-options
                      :options="columns"
                      option-value="name"
                      class="q-mx-lg"
                    >
                      <template v-slot:option="scope">
                        <q-item
                          v-bind="scope.itemProps"
                          v-on="scope.itemEvents"
                          v-if="!scope.opt.required"
                        >
                          <q-item-section avatar>
                            <q-toggle color="blue" v-model="visibleColumns" :val="scope.opt.name" />
                          </q-item-section>
                          <q-item-section style="min-width:60px">
                            {{ scope.opt.label }}
                          </q-item-section>
                        </q-item>
                      </template>
                    </q-select>
                    <q-toggle
                      v-model="searchToggle"
                      left-label
                      label="搜索"
                      color="blue"
                      checked-icon="check"
                      unchecked-icon="clear"
                      keep-color
                    />
                    <q-btn
                      flat round dense
                      :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
                      @click="props.toggleFullscreen"
                      class="q-ml-md"
                    />
                  </template>
                  <template v-if="searchToggle" v-slot:top-row="props">
                    <q-tr :props="props">
                      <q-td>
                        <q-btn color="primary" dense flat icon="search" @click="listGet({ pagination: pagination, filter: searchForm })"/>
                      </q-td>
                      <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
                        <q-input dense outlined v-model="searchForm[col.name]"/>
                      </q-td>
                    </q-tr>
                  </template>
                  <template v-slot:header="props">
                    <q-tr :props="props">
                      <q-th>
                        <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
                      </q-th>
                      <q-th v-for="col in props.cols" :key="col.name" :props="props">
                        {{ col.label }}
                      </q-th>
                    </q-tr>
                  </template>
                  <template v-slot:body="props">
                    <q-tr :props="props">
                      <q-td width="52">
                        <q-checkbox dense v-model="props.selected" />
                      </q-td>
                      <!-- <q-td key="action" :props="props">
                        <q-btn-dropdown
                          color="blue"
                          size="sm"
                          dense
                          menu-anchor="bottom left"
                          menu-self="top left"
                          content-class="text-grey"
                          icon="settings">
                          <q-list dense>
                            <q-item clickable v-close-popup @click="edit(props.row)">
                              <q-item-section>
                                <q-item-label>修改</q-item-label>
                              </q-item-section>
                            </q-item>
                            <q-item clickable v-close-popup @click="delRow(props.row)">
                              <q-item-section>
                                <q-item-label>删除</q-item-label>
                              </q-item-section>
                            </q-item>
                          </q-list>
                        </q-btn-dropdown>
                      </q-td> -->
                      <q-td key="name" :props="props">{{ props.row.name }}</q-td>
                      <q-td key="phone" :props="props">{{ props.row.phone  }}</q-td>
                      <q-td key="email" :props="props">{{ props.row.email  }}</q-td>
                      <q-td key="createUserName" :props="props">{{ props.row.createUserName }}</q-td>
                      <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
                    </q-tr>
                    <q-tr v-show="props.expand" :props="props">
                      <q-td colspan="100%">
                      </q-td>
                    </q-tr>
                  </template>
                  <template v-slot:pagination="props">
                    <q-pagination
                      v-model="pagination.page"
                      color="blue"
                      :max-pages="5"
                      :max="pages"
                      :boundaryLinks="true"
                      :directionLinks="true"
                    />
                    共 {{ total }} 条
                  </template>
                </q-table>
              </q-tab-panel>
            </q-tab-panels>
          </q-card-section>
        </q-card>
      </div>
    </q-list>
    <q-dialog
      v-model="addDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 40vw">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addEdit === 1? '新增' : '修改'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <div :class="$v.addEditForm.name.$error?'text-negative': ''">名称</div>
              <q-input
                v-model="addEditForm.name"
                error-message="该字段为必填项"
                :error="$v.addEditForm.name.$error"
                @blur="$v.addEditForm.name.$touch"
                dense hint/>
            </div>
            <div class="col-12">
              <div :class="$v.addEditForm.sn.$error?'text-negative': ''">序号</div>
              <q-input
                v-model="addEditForm.sn"
                error-message="该字段为必填项"
                :error="$v.addEditForm.sn.$error"
                @blur="$v.addEditForm.sn.$touch"
                dense hint/>
            </div>
          </div>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="取消" color="primary" v-close-popup/>
          <q-btn flat label="保存" color="primary" :loading="loadingSave" @click="saveHeader"/>
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 40vw">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '新建联系人':'修改联系人'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:30vh;max-height:60vh'" class="scroll">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <div  :class="$v.addOrEditForm.name.$error?'text-negative': ''">名称</div>
              <q-input
                :error="$v.addOrEditForm.name.$error"
                @blur="$v.addOrEditForm.name.$touch"
                v-model="addOrEditForm.name"
                dense hint/>
            </div>
            <div class="col-12">
              <div  :class="$v.addOrEditForm.phone.$error?'text-negative': ''">电话</div>
              <q-input
                type="number"
                :error="$v.addOrEditForm.phone.$error"
                @blur="$v.addOrEditForm.phone.$touch"
                v-model="addOrEditForm.phone"
                dense hint/>
            </div>
            <div class="col-12">
              <div  :class="$v.addOrEditForm.email.$error?'text-negative': ''">邮箱</div>
              <q-input
                :error="$v.addOrEditForm.email.$error"
                @blur="$v.addOrEditForm.email.$touch"
                v-model="addOrEditForm.email"
                dense hint/>
            </div>
          </div>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" color="primary" :loading="loadingSave" @click="saveHandler" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<style lang="stylus" scoped>
  /deep/.q-item
    min-height 30px
    max-height 35px
  .h-td-maxwidth
    max-width 200px
  #treeName
    flex-wrap nowrap
  #name
    padding 0px
</style>

<script>
import { isEmail } from 'src/utils/my.validators.js'
import { transformToTreeFormat } from 'src/utils/fns'
import { required } from 'vuelidate/lib/validators'
export default {
  name: 'Contacts',
  data () {
    return {
      // 树新增
      baseItemForm: {
        name: ''
      },
      addDialog: false,
      addEdit: 1,
      addEditForm: {
        id: '',
        parentId: '',
        sn: '100',
        type: '',
        name: ''
      },
      ids: [],
      tabs: 'item',
      tab: 'mails',
      nodeSelectedHeader: 'root',
      nodeSelected: '',
      nodeExpanded: [],
      nodeData: [],
      id: '',
      searchToggle: false,
      searchForm: {
        name: '',
        createTime: '',
        phone: '',
        email: '',
        createUserName: ''
      },
      selected: [],
      visibleColumns: [
        // 'action',
        'name',
        'phone',
        'email',
        'createTime',
        'createUserName'
      ],
      // 当加入 required: true 属性时  visibleColumns 对当前字段无效
      columns: [
        // { name: 'action', align: 'center', label: '操作' },
        { name: 'name', required: true, label: '名称', align: 'left', field: 'name', sortable: true },
        { name: 'phone', label: '联系人电话', align: 'left', field: 'email', sortable: true },
        { name: 'email', label: '联系人邮箱', align: 'left', field: 'phone', sortable: true },
        { name: 'createUserName', label: '创建人', align: 'left', field: 'createUserName', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      data: [],
      total: 0,
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      // dialog
      addOrEdit: 1, // 1 新增  2 修改
      loadingSave: false,
      addOrEditDialog: false,
      maximizedToggle: false,
      addOrEditTab: 'tab1',
      addOrEditForm: {
        name: '',
        phone: '',
        email: ''
      }
    }
  },
  computed: {
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    }
  },
  validations: {
    addOrEditForm: {
      name: { required },
      phone: { required },
      email: {
        required,
        isEmail
      }
    },
    addEditForm: {
      name: { required },
      sn: { required }
    }
  },
  watch: {
    'nodeSelected' () {
      // 是否显示联系人
      this.nodeSelectedHeader = this.$refs.orgTree.getNodeByKey(this.nodeSelected).header
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
      this.getOneTree()
    },
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    }
  },
  mounted () {
    this.id = this.$route.params.id
    this.init()
    this.getTree()
  },
  methods: {
    init () {
      // this.listGet({
      //   pagination: this.pagination,
      //   filter: this.searchForm
      // })
      // this.getTree()
    },
    async getOneTree () {
      await this.$api({
        method: 'get',
        url: `/mdm/supplierOrgTree/findById/${this.nodeSelected}`,
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.baseItemForm = { ...data }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    // 树删除
    delTree (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除组织：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/supplierOrgTree/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
            this.getTree()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    },
    // 树修改
    editTree (props) {
      this.addEditForm = {
        type: props.type,
        id: props.id,
        name: props.name,
        parentId: props.parentId,
        sn: props.sn
      }
      this.addOrEdit = 2
      this.addDialog = true
    },
    // 树查询
    async getTree () {
      await this.$api({
        method: 'post',
        url: '/mdm/supplierOrgTree/queryAll',
        params: {
          supplierMainId: this.id
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(data)
          data.forEach(item => {
            this.ids.push(item.id)
            if (item.type === 1 && item.parentId === '0') {
              item.header = 'root'
            } else if (item.type === 1 && item.parentId !== '0') {
              item.header = 'company'
            } else if (item.type === 2) {
              item.header = 'department'
            } else if (item.type === 3) {
              item.header = 'post'
            }
            // item.name = String(item.code) + String(item.name)
          })
          this.nodeExpanded = this.ids
          this.nodeData = transformToTreeFormat(data, 'id', 'parentId', 'children')
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    // 树新增
    addTree (props, type) {
      if (props === 0) {
        this.addEditForm = {
          id: '',
          type: '1',
          parentId: '0',
          sn: '100',
          name: ''
        }
      }
      if (props.header === 'root' || props.header === 'company') {
        this.addEditForm = {
          id: '',
          type: type,
          parentId: props.id,
          sn: '100',
          name: ''
        }
      }
      if (props.header === 'department') {
        this.addEditForm = {
          id: '',
          type: type,
          parentId: props.id,
          sn: '100',
          name: ''
        }
      }
      if (props.header === 'post') {
        this.addEditForm = {
          id: '',
          type: type,
          parentId: props.id,
          sn: '100',
          name: ''
        }
      }
      this.addEdit = 1
      this.$v.addEditForm.$reset()
      this.addDialog = true
    },
    async saveHeader () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addEditForm.$error) {
        this.addEditForm.supplierMainId = this.id
        this.loadingSave = true
        await this.$api({
          method: 'put',
          url: this.addOrEdit === 1 ? '/mdm/supplierOrgTree/add' : '/mdm/supplierOrgTree/update',
          params: this.addEditForm,
          emulateJSON: true,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addDialog = false
            this.getTree()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSave = false
      } else {
        this.errorCopy = true
      }
    },
    remove () {
      console.log('11111111')
    },
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: '/mdm/supplierLink/query',
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          orgTreeId: this.nodeSelected,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.total = data.total
          this.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    },
    async add () {
      this.addOrEdit = 1
      this.addOrEditTab = 'tab1'
      this.addOrEditForm = {
        id: '',
        name: '',
        phone: ''
      }
      this.$v.addOrEditForm.$reset()
      this.addOrEditDialog = true
    },
    async edit (row) {
      await this.$api({
        method: 'get',
        url: `/mdm/supplierLink/findById/${row.id}`,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.addOrEditDialog = true
          this.addOrEditForm = { ...data }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.addOrEdit = 2
      this.addOrEditTab = 'tab1'
      this.$v.addOrEditForm.$reset()
    },
    async saveHandler () {
      console.log(this.addOrEditForm)
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.addOrEditForm.orgTreeId = this.nodeSelected
        this.loadingSave = true
        await this.$api({
          method: 'put',
          url: this.addOrEdit === 1 ? '/mdm/supplierLink/add' : '/mdm/supplierLink/update',
          params: this.addOrEditForm,
          emulateJSON: true,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addOrEditDialog = false
            this.getTree()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
        this.loadingSave = false
      } else {
        this.errorCopy = true
      }
    },
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除联系人：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/supplierLink/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
            this.getTree()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    }
  }
}
</script>
